package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@Component
public class RedisIdWorker {
    //开始时间戳
    private static final long BEGIN_TIMESTAPE=1704067200L;
    //序列号的位数
    private static final int COUNT_BITS=32;
    private StringRedisTemplate stringRedisTemplate;
    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate=stringRedisTemplate;
    }
    public long nextId(String KeyPrefix){
        //生成时间数
        LocalDateTime time=LocalDateTime.now();
        Long nowsecond=time.toEpochSecond(ZoneOffset.UTC);
        Long timestamp=nowsecond-BEGIN_TIMESTAPE;
        //生成序列号
        //获取当前日期，精确到天
        String date= time.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //自增长
        Long count=stringRedisTemplate.opsForValue().increment("icr:"+KeyPrefix+":"+date);

        //拼接并返回

        return timestamp<<COUNT_BITS |count;
    }
 /*   public static void main(String[] args){
        LocalDateTime time=LocalDateTime.of(2024,1,1,0,0,0);
        Long second=time.toEpochSecond(ZoneOffset.UTC);
        System.out.println(second);
    }*/
}
